package com.qf.service.impl;

import com.qf.mapper.FarmMapper;
import com.qf.mapper.SysUserMapper;
import com.qf.model.Farm;
import com.qf.model.SysUser;
import com.qf.page.PageResult;
import com.qf.page.QueryPageBean;
import com.qf.service.FarmService;
import com.qf.service.SysUserService;
import com.qf.utils.UUIDUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.List;

@Service
public class FarmServiceImpl implements FarmService {
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private FarmMapper farmMapper;

    @Override
    @Transactional
    public int add(Farm farm) {
        farm.setUpdateTime(new Date());
        return farmMapper.add(farm);
    }

    @Override
    public Farm findById(int id) {
        return farmMapper.findById(id);
    }


    @Override
    @Transactional
    public int edit(Farm farm) {
        farm.setUpdateTime(new Date());
        int i = farmMapper.edit(farm);
        return i;
    }


    @Override
    @Transactional
    public int delete(int id) {
        return farmMapper.delete(id);
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {

        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String username = null;
        if (principal instanceof UserDetails) {
            username = ((UserDetails)principal).getUsername();
        } else {
            username = principal.toString();
        }
        System.out.println("username---------->"+username);
        int userId = sysUserMapper.findUserByUsername(username).getId();


        Integer CurrentPage = queryPageBean.getCurrentPage();
        Integer PageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageResult pageResult = new PageResult();
        List<Farm> rows = farmMapper.findPage((CurrentPage - 1) * PageSize, PageSize, queryString,userId);
        for (Farm row : rows) {
            SysUser sysUser = sysUserMapper.findById(row.getUserId());
            row.setSysUser(sysUser);
        }
        Long total = farmMapper.count(queryString,userId);
        pageResult.setRows(rows);
        pageResult.setTotal(total);
        return pageResult;
    }

    @Override
    public List<Farm> findAll() {
        return farmMapper.findAll();
    }
}
